import logging as log
import json

try:
    from urllib.parse import urlencode
    from urllib.request import Request, urlopen
except ImportError as e:
    from urllib.parse import urlencode
    from urllib.request import Request, urlopen
try:
    from info_config import db_platform_url
    from info_config import message_send_url
    from info_config import backup_info_into_dbpt_url
    from info_config import get_mongodb_batck_info_url
    from info_config import username
    from info_config import password
except Exception as e:
    from info_config import db_platform_url
    from info_config import message_send_url
    from info_config import backup_info_into_dbpt_url
    from info_config import get_mongodb_batck_info_url
    from info_config import username
    from info_config import password


def message_format(body):
    # log.info(str(body))
    try:
        # message = bytes.decode(body)
        message = str(body)
        # message1 = json.loads(message)
        message_eval = eval(message)
        for key, value in message_eval.items():
            if isinstance(value, bytes):
                message_eval.update({key: str(value, encoding="utf-8")})
        return message_eval
    except Exception as e:
        log.exception(str(e))
        return


def get_token(username, password):
    message = {
        'eauth': "pam",
        "username": username,
        "password": password
    }
    auth_url = "/auth/token/user_login"
    request_url = "{db_platform_url}{auth_url}".format(db_platform_url=db_platform_url,
                                                       auth_url=auth_url)
    request = Request(request_url, urlencode(message).encode())
    body = urlopen(request).read().decode()
    token_info = message_format(body)
    token = token_info.get("token")
    log.debug(token)
    return "bearer " + token


def info_interactive_with_dbpt(db_platform_url,
                               suffix_url,
                               args_send,
                               method="POST"):
    token_get = get_token(username=username, password=password)
    args_send_formated = json.dumps(args_send)
    base_url = db_platform_url
    request_url = "{}{}".format(base_url, suffix_url)
    req = Request(url=request_url,
                  data=bytes(
                      args_send_formated.encode("utf-8")),
                  method="POST")

    log.debug(request_url)
    req.add_header("Content-type", "application/json; charset=UTF-8")
    req.add_header("Authorization", token_get)
    with urlopen(req) as resp:
        response_data = json.loads(resp.read().decode("utf-8"))
        log.debug(response_data)
    return response_data


def backup_info_into_dbpt(backup_info):
    args_send = backup_info
    info_interactive_with_dbpt(db_platform_url=db_platform_url, suffix_url=backup_info_into_dbpt_url,
                               args_send=args_send)


def send_message(info_send):
    args_send = {"ding_receiver": 1, "msgtype": "text", "text": info_send}
    info_interactive_with_dbpt(db_platform_url=db_platform_url, suffix_url=message_send_url, args_send=args_send)


def get_mongodb_backup_batch_info(batch_id, backup_host):
    args_send = {"batch_id": batch_id, "backup_host": backup_host}
    msg_from_dbpt = info_interactive_with_dbpt(db_platform_url=db_platform_url, suffix_url=get_mongodb_batck_info_url,
                                               args_send=args_send)
    backup_info = msg_from_dbpt.get('msg')
    return backup_info


if __name__ == "__main__":
    send_message("hehe test")
